package com.fulu.game.bi.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fulu.game.bi.config.BizConfig;
import com.fulu.game.bi.entity.bo.channel.DictItemBO;
import com.fulu.game.bi.entity.po.DictItem;
import com.fulu.game.bi.mysql.bi.DictItemDao;
import com.fulu.game.bi.redis.service.statistics.FundsStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * @Author: liuxiao
 * @Date: 2021/7/27 9:39 上午
 */
@Slf4j
@RestController
@RequestMapping("/api/v1")
public class DataStatistics {


    @Autowired
    private FundsStatisticsService fundsStatisticsService;
    @Autowired
    private BizConfig configProperties;
    @Autowired
    private DictItemDao dictItemDao;


    @RequestMapping("/test/exportExcel")
    @ResponseBody
    public String exportExcel() {
        fundsStatisticsService.refreshTable();
        String fundsUrl = fundsStatisticsService.getFundStatisticsFile();
        String incomeUrl = fundsStatisticsService.getIncomeFile();
        String overViewUrl = fundsStatisticsService.getOverviewFile();
        int month = DateUtil.thisMonth() + 1;
        String finaMonth = month < 10 ? "0" + month : month + "";
        int day = DateUtil.thisDayOfMonth();
        String finaDay = day < 10 ? "0" + day : day + "";
        String date = finaMonth + finaDay;
        String msg = "- [业务总览" + date + "](" + overViewUrl + ") \n - " + "[营收报表" + date + "](" + incomeUrl + ") \n - " + "[资金报表" + date + "](" + fundsUrl + ")";

        log.info("msg 文件：{}", msg);

        DictItemBO dictItemBO = new DictItemBO();
        dictItemBO.setCode("BI_DINGTALK_CONFIG_JSON");
        List<DictItem> dictItemList = dictItemDao.findByParameter(dictItemBO);
        if (CollectionUtils.isEmpty(dictItemList)) {
            log.error("字典参数配置错误");
        }
        String jsonAry = dictItemList.get(0).getVal();

        JSONArray jsonArray = JSONObject.parseArray(jsonAry);
        for (int i = 0; i < jsonArray.size(); i++) {
            String url = jsonArray.getJSONObject(i).getString("url");
            String secret = jsonArray.getJSONObject(i).getString("secret");
            JSONObject template = jsonArray.getJSONObject(i).getJSONObject("templa");
            pushMsg(msg, url, secret, template);
        }
        return msg;
    }

    @Scheduled(cron = "0 25 7 * * ? ")
    public void realtime() {
        String env = configProperties.getRocketmq().getConsumer().getEvn();
        log.info("env环境：{}", env);
        if (!"PROD".equals(env) && !isOpen()) {
            return;
        }
        exportExcel();
    }


    private boolean isOpen() {
        DictItemBO dictItemBO = new DictItemBO();
        dictItemBO.setDictCode("EXPORT_STATISTICS_CHECK");
        dictItemBO.setCode("EXPORT_STATISTICS_CHECK_SWICH");
        List<DictItem> list = dictItemDao.findByParameter(dictItemBO);
        return CollectionUtil.isNotEmpty(list) && Objects.equals(list.get(0).getVal(), "1");
    }


    private void pushMsg(String msg, String url, String secret, JSONObject template) {
        try {
            log.info("url:{},secret:{},template:{}", url, secret, template);
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            HttpUtil.createPost(url + "&timestamp=" + timestamp + "&sign=" + sign)
                    .body(String.format(template.toJSONString(), msg)).timeout(20000).execute();
            log.info("消息发送成功{}", msg);
        } catch (Exception e) {
            log.error("推送钉钉消息异常", e);
        }
    }

    @RequestMapping("/dict/update")
    public String dictUpdate(DictItemBO dictItemBO) {
        if (dictItemBO.getId() != null) {
            dictItemDao.update(dictItemBO);
        }
        return "success";
    }

    @RequestMapping("/dict/add")
    public String dictAdd(DictItemBO dictItemBO) {
        dictItemDao.create(dictItemBO);
        return "success";
    }
}
